from django.core.cache import cache
from django.http import HttpRequest, JsonResponse
from django.shortcuts import render
from django.views import View

from apps.area.models import Area

# Create your views here.
class AreaView(View):
    def get(self, request: HttpRequest):
        province_list=cache.get('provinces')
        if province_list is None:
            provinces=Area.objects.filter(parent=None)
            province_list=[]
            for province in provinces:
                province_list.append({
                    'id':province.id,
                    'name':province.name
                })
            cache.set('provinces', province_list, 3600*24)
        return JsonResponse({'code':0,'errmsg':'ok','province_list':province_list})

class CityView(View):
    def get(self, request: HttpRequest, city_id):
        data_list=cache.get('city%s'%city_id)
        if data_list is None:
            cities=Area.objects.filter(parent=city_id)
            data_list=[]
            for city in cities:
                data_list.append({
                    'id':city.id,
                    'name':city.name
                })
            cache.set('city%s'%city_id, data_list, 3600*24)
        return JsonResponse({'code':0,'errmsg':'ok','sub_data':{'subs':data_list}})
